package com.inews.business.web.excel;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.document.AbstractExcelView;

import com.inews.base.utils.ExcelUtil;
import com.inews.base.utils.Servlets;
import com.inews.base.vo.ExtData;

import com.inews.business.service.IPracticeInfoService;

import com.inews.business.vo.PracticeInfoVo;
@Component
public class PracticeInfoExcelView extends AbstractExcelView {
	@Autowired
	private IPracticeInfoService service;
     
	
	@Override
	protected void buildExcelDocument(Map<String, Object> model,
			HSSFWorkbook workbook, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String jsonFilter = request.getParameter("jsonFilter");
		logger.info("接收到的查询条件json：" + jsonFilter);
		Map<String, Object> searchParams = Servlets.getParametersStartingWith(jsonFilter, "search_");
		ExtData<PracticeInfoVo> extData = service.exportExcel(searchParams);
		List<PracticeInfoVo> voList = extData.getRoot();

		String fileName = URLEncoder.encode("教师企业实践经历信息", "UTF-8");
		// 设置response方式,使执行此controller时候自动出现下载页面,而非直接使用excel打开
		response.setContentType("APPLICATION/OCTET-STREAM");
		response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");

		// 产生Excel表头
		HSSFSheet sheet = workbook.createSheet("教师企业实践经历信息");
		HSSFRow header = sheet.createRow(0); // 第0行
		List<String> keyValue=ExcelUtil.PracticeValue;
		for(int i=0;i<keyValue.size();i++){
			header.createCell(i).setCellValue(keyValue.get(i).split(":")[0]);
		}
		
	
		// 填充数据
		int rowNum = 1;
		for (PracticeInfoVo vo : voList) {
			HSSFRow row = sheet.createRow(rowNum++);
			for(int i=0;i<keyValue.size();i++){
				HSSFCell cell=row.createCell(i);
				if(keyValue.get(i).split(":")[1].toLowerCase().endsWith("date")){
				String value=BeanUtils.getProperty(vo, keyValue.get(i).split(":")[1]);
					if(value!=null&&!"".equals(value)){
					String dateformat=DateFormatUtils.format(DateUtils.parseDate(value, new String[]{"yyyyMMdd"}),"yyyy-MM-dd");
					cell.setCellValue(dateformat);
					}
					else cell.setCellValue("");
				}
				else
				cell.setCellValue(BeanUtils.getProperty(vo, keyValue.get(i).split(":")[1]));
			}

		}

	}
}
